package com.dominator.api.utils.api;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.dominator.api.common.util.MyUtil;
import com.dominator.api.enums.ReqEnums;
import com.dominator.api.mybatis.tuser.TUserEntity;
import com.dominator.api.mybatis.tuser.TUserMapper;
import com.dominator.api.utils.exception.ApiException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ApiUtils {

    @Autowired
    TUserMapper tUserMapper;


    @Autowired
    StringRedisTemplate stringRedisTemplate;


    /**
     *  获取token
      * @param userEntity
     * @return
     */
    public String getToken(TUserEntity userEntity){
        String token="";
        token= JWT.create().withAudience(userEntity.getId())
                .sign(Algorithm.HMAC256(userEntity.getPassword()));
        //redis操作
        stringRedisTemplate.opsForValue().set("user_token:"+userEntity.getId(),token,Constants.redisCountDown);
        return token;
    }


    /**
     * 检查token
     * @param token
     */
    public void checkToken(String token){
        // 执行认证
        if (token == null) {
            throw new ApiException(ReqEnums.REQ_TOKEN_NULL);
        }
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            log.error("用户id解密失败：token="+token);
            throw new ApiException(ReqEnums.REQ_TOKEN_ILLEGAL);
        }



        TUserEntity tUserEntity = tUserMapper.selectByKey(userId);
        if (MyUtil.isEmpty(tUserEntity)){
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }else if (Constants.is_valid.no.equals(tUserEntity.getIs_valid())){
            throw new ApiException(ReqEnums.REQ_USER_IS_NOT_VALID);
        }

        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(tUserEntity.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            log.error("密码解密失败：token="+token);
            throw new ApiException(ReqEnums.REQ_TOKEN_ILLEGAL);
        }


        //滑动过期
        String redisToken=stringRedisTemplate.opsForValue().get("user_token:"+tUserEntity.getId());
        if (token.equals(redisToken)){
            stringRedisTemplate.opsForValue().set("user_token:"+tUserEntity.getId(),token,Constants.redisCountDown);
        }





    }

}
